#! /usr/bin/env perl
use lib ($ENV{RLWRAP_FILTERDIR} or ".");
use RlwrapFilter;
use strict;

my $filter = new RlwrapFilter;
my $name = $filter->name;

$filter->help_text("Usage: rlwrap -z '$name <filter-command>' <command>\n"
                   . "Filter <command> output through <filter-command>");


my $filter_command = join ' ', @ARGV;
die $filter -> help_text . "\n" if not $filter_command and $ENV{RLWRAP_COMMAND_PID};

$filter->output_handler(sub {""});
$filter->prompt_handler(\&prompt);

$filter->run;

sub prompt {
    my $prompt = shift;

    my $output = $filter->cumulative_output;
    $output =~ s/\r//g;

    open (PIPE, "| $filter_command")
        or die "Failed to create pipe: $!";
    print PIPE $output;
    close PIPE;

    return $prompt;
}
